package com.example.demo.Utils.RedisUtils;

import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisUtil {
    @Resource
    public RedisTemplate<String, String> redisTemplate;

    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }


    public void set(String key, String value) {
        log.info("已设置键值为:" + key);
        redisTemplate.opsForValue().set(key, value);
    }


    public void set(String key, String value, long time) {
        if (time > 0) {
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
        } else {
            redisTemplate.opsForValue().set(key, value);
        }
    }
    public long size(String key) {
        return redisTemplate.opsForSet().size(key);
    }


    public void add(String key, Map<String, String> map) {
        redisTemplate.opsForHash().putAll(key, map);
    }

    public Long delete(String key, String... hashKeys) {
        return redisTemplate.opsForHash().delete(key, (Object) hashKeys);
    }
    public void setObject(String key, Object object) {
        String s = JSON.toJSONString(object);
        redisTemplate.opsForValue().set(key, s,8,TimeUnit.HOURS);
    }

    public void clear() throws IOException {
        redisTemplate.execute((RedisCallback<Object>) connection -> {
            connection.serverCommands();
            return null;
        });
    }

    public void deleteKeysStartingWith(String prefix) {
        log.info("现在开始删除前缀清空redis");
        log.info("删除的键值为:{}", prefix);
        Set<String> keys = redisTemplate.keys(prefix + "*");
        redisTemplate.delete(keys);
        log.info("已删除:{}条数据", keys.size());
    }

}
